package com.example.demo.bigfileupload;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * 文件分片
 * 方便后端自测文件操作逻辑
 */
public class ChunkFile {
    private static final String PATH = "D:/file/test/";
    private static final String FILE_NAME = "稻香-周杰伦";
    private static final String FILE_EXTENSION = ".mp4";
    private static final Integer CHUNK_SIZE = 104857600; // 100MB

    public static void main(String[] args) throws Exception {
        File file = new File(PATH, FILE_NAME + FILE_EXTENSION);
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        long size = FileUtil.size(file);
        // 分片数
        int chunkNum = (int) Math.ceil((double) size / CHUNK_SIZE);
        byte[] bytes;
        // 循环进行文件读取并写入数据至分片文件
        for (int i = 0; i < chunkNum; i++) {
            // 文件当前偏移量
            long pointer = randomAccessFile.getFilePointer();
            int len = i == chunkNum - 1 ? (int) (size - pointer) : CHUNK_SIZE;
            bytes = new byte[len];
            randomAccessFile.read(bytes, 0, len);
            FileUtil.writeBytes(bytes, new File(PATH, i + FILE_EXTENSION));
        }
    }
}
